/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.fsts.server;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.List;

import com.fsts.entity.PublicKey;

/**
 * TC服务中心处理器
 * 
 * @method 处理用户对服务器的各种请求
 * @version 1.0
 * @since JDK1.6(建议)
 */
public class TrustedCenterHandler implements Runnable {
	private Socket s;
	private PrintWriter out;
	private List<TrustedCenterHandler> handlers;
	private static TCDao tc = new TCDao();
	private static UserDao ud = new UserDao();

	public TrustedCenterHandler(Socket s) {
		super();
		this.s = s;
	}

	public List<TrustedCenterHandler> getHandlers() {
		return handlers;
	}

	public void setHandlers(List<TrustedCenterHandler> handlers) {
		this.handlers = handlers;
	}

	public void run() {
		BufferedReader in = null;
		try {
			in = new BufferedReader(new InputStreamReader(s.getInputStream()));
			out = new PrintWriter(new OutputStreamWriter(s.getOutputStream()));
			while (true) {
				String req = in.readLine(); // 请求参数
				if (req.indexOf("getTCPublicKey") >= 0) {
					PublicKey key = tc.getPublicKey();
					out.println(key.toString());
					out.flush();
					continue;
				} else if (req.indexOf("register") >= 0) {
					String result = ud.register(req);
					// result 返回结果..输出给用户
					if (result.equals("fail")) {
						out.println("fail");
					} else {
						out.println(result);
						out.flush();
					}
					break;
				} else if (req.indexOf("login") >= 0) {
					UserDao u = new UserDao();
					if (u.login(req)) {
						out.println("ok");
					} else {
						out.println("fail");
					}
				} else if (req.indexOf("checkOnlineUser") >= 0) {
					// TODO 检查用户在线数
				}
				sendAll(req);
				break;
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				in.close();
				out.close();
				s.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	private void sendAll(String message) {
		for (TrustedCenterHandler h : handlers) {
			h.send(message);
		}
	}

	private void send(String message) {
		try {
			out.println(message);
			out.flush();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}
